<template>
    <div class="pop-selectitem-list">
        <el-dialog title="选择商品" :visible.sync="dialogVisible" top="5vh" width="50%" :close-on-click-modal="false"
            @close="closeDialog">
            <div class="search-box" v-show="!is_bill">
                <div class="search-box-select">
                    <el-form :model="searchform">
                        <el-form-item>
                            <el-cascader size="small" v-model="searchform.catid" :options="cat_ls" class="sele-w"
                                :props="propsdata" @change="changeList"></el-cascader>
                        </el-form-item>
                        <el-form-item>
                            <el-select size="small" v-model="searchform.storeid" class="sele-w"
                                popper-class="method-box" @change="changeList">
                                <el-option v-for="item in qty_ls_data" :key="item.id" :label="item.name"
                                    :value="item.id">
                                    <div class="option-title">
                                        {{ item.name }}
                                    </div>
                                    <div class="option-doc">{{ item.num }}</div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-select size="small" v-model="searchform.is_stock" @change="changeList">
                                <el-option v-for="item in godd_status_ls" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="list-box" v-infinite-scroll="loadFun">
                    <!-- list_data -->
                    <div class="list" v-if="vList && vList.length > 0">
                        <div class="list-row" v-for="item in vList" :key="item.id" @click.stop="chegoodFun(item)">
                            <div class="list-info">
                                <div class="img-box">
                                    <img :src="item.imgs ? item.imgs : img_buf" alt="" />
                                </div>
                                <div class="info-box">
                                    <div class="title bold"> {{ item.title }} </div>
                                    <div class="phone flex_between">
                                        <div>
                                            <span class="font_red mr20">价格：{{ item.price || '0.00' }}</span>
                                            <span>库存：{{ item.qty }}</span>
                                        </div>
                                        <div class="f-num" v-if="item.total_num > 0">{{ item.total_num }}</div>
                                    </div>
                                    <div class="tag-box">
                                        <span v-for="(tag_item, tag_index) in item.tagsInfo" :key="tag_index"
                                            :style="{ backgroundColor: color_data[tag_index], }">
                                            {{ tag_item }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <el-empty v-else description="暂无商品" :image-size="80"></el-empty>
                    <div style="height: 80px;"></div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <div class="summary-info">
                        <div class="summary-item">
                            <span class="summary-label">数量</span>
                            <span class="summary-value quantity">{{ isNaN(totalNum) ? 0 : totalNum }}</span>
                        </div>
                        <div class="summary-divider"></div>
                        <div class="summary-item">
                            <span class="summary-label">总额</span>
                            <span class="summary-value amount">￥{{ isNaN(totalpic) ? '0.00' : parseFloat(totalpic).toFixed(2) }}</span>
                        </div>
                    </div>
                    <div class="action-buttons">
                        <el-button @click="cancelFun" size="small" class="btn-cancel">取 消</el-button>
                        <el-button type="primary" @click="chooseGoods" size="small" class="btn-confirm" v-show="!is_bill">选 好 了</el-button>
                    </div>
                </div>
            </div>
            <chiceitem ref="chiceitemRef" v-show="is_bill" @cancelFun="cancelFun" @determineFilling="determineFilling" :tabType="tabType">
            </chiceitem>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, computed,defineProps } from '@vue/composition-api'
import config from "@/js/conf/Config.js";
import staticConst from "@/js/const/StaticConst.js";
import chiceitem from "@/components/commV2/chiceSkuCkModel/chiceitem.vue"
const { proxy } = getCurrentInstance()

const props = defineProps({
    tabType: {
        type: String,
        default: '',
    },
})

const chiceitemRef = ref(null)
const emit = defineEmits(['determineFun'])

// Reactive data
const img_buf = ref(staticConst.GOOD_IMG)
const is_bill = ref(false)
const is_soll = ref(false)
const dialogVisible = ref(false)

const searchform = reactive({
    catid: "",
    pfrom: 0,
    pnum: 20,
    page: "1",
    idyun: "",
    storeid: 0,
    is_stock: "",
})

const cat_ls = ref([])
const qty_ls_data = ref([])
const list_data = ref([]) //展示的产品列表
const list_data_back = ref([]) //最终选好的产品列表
const edit_spec_data = ref([])
const totalNum = ref(0)
const totalpic = ref(0)

const propsdata = reactive({
    children: "son",
    label: "title",
    value: "id",
    expandTrigger: "hover",
    checkStrictly: true,
})

const color_data = ref([
    "#3989fc",
    "#ee464b",
    "#19c56b",
    "#fd641c",
    "#3989fc",
    "#ee464b",
])

const godd_status_ls = ref([{
    id: "",
    name: "全部产品",
},
{
    id: "1",
    name: "有货产品",
},
{
    id: "2",
    name: "无货产品",
},
{
    id: "3",
    name: "上架产品",
},
{
    id: "4",
    name: "下架产品",
},
{
    id: "5",
    name: "已选产品",
},
])

// Methods
const initData = async (data) => {
    list_data_back.value = []
    totalNum.value = 0
    totalpic.value = 0
    searchform.idyun = data.shopid_yd
    emptyData()
    await getlistdata()
    if (cat_ls.value.length == 0) {
        await getCatListFun()
    }
}

// 筛选
const changeList = () => {
    if (searchform.is_stock == 5) {
        emptyData()
    } else {
        emptyData()
        getlistdata()
    }
}

// 点击产品
const chegoodFun = (item) => {
    is_bill.value = true
    chiceitemRef.value.initData(item)
}

// 滚动加载
const loadFun = () => {
    if (is_soll.value) return
    searchform.pfrom += 20
    getlistdata()
}

// 取消
const cancelFun = () => {
    if (is_bill.value) {
        is_bill.value = false
    } else {
        dialogVisible.value = false
    }
}

const shopFillData = (data) => {
    list_data_fill.value = data
}

const list_data_fill = ref([])
const vList = computed(() => {
    list_data.value.map(item => {
        return {
            ...item,
        }
    })
    return list_data.value
})

// 获取产品列表
const getlistdata = async () => {
    is_soll.value = true
    let url = config.GOODS_LIST
    let param = Object.assign({}, searchform)
    param.catid = param.catid
        ? param.catid[param.catid.length - 1]
        : ""
    let res = await proxy.$api({ url: url, data: param })
    if (res.status == 1) {
        if (res.data.store_ls && qty_ls_data.value.length == 0) {
            qty_ls_data.value = res.data.store_ls
        }
        if (res.data.goodsInfo) {
            res.data.goodsInfo.map((v) => {
                v.total_num = 0
                v.total_pic = 0
                if (v.tagsInfo) {
                    v.tagsInfo.unshift("上架")
                } else {
                    v.tagsInfo = ["上架"]
                }
                if (edit_spec_data.value.length > 0) {
                    edit_spec_data.value.map((vs) => {
                        if (v.id == vs.id) {
                            v.spec_data = vs.spec_data
                            v.total_num = vs.total_num
                            v.total_pic = vs.total_pic
                        }
                    })
                }
            })
            list_data.value = list_data.value.concat(res.data.goodsInfo)
            list_data_back.value = list_data_back.value.concat(res.data.goodsInfo)
            let map = new Map()
            for (let item of list_data_back.value) {
                map.set(item.id, item)
            }
            list_data_back.value = [...map.values()]
            setTimeout((v) => {
                is_soll.value = false
            }, 200)
        } else {
            is_soll.value = true
        }
    }
}

// 获取分类列表
const getCatListFun = async () => {
    let url = config.GDPRE_CAT_LS
    let param = {}
    let res = await proxy.$api({ url: url, data: param })
    if (res.status == 1 && res.data) {
        res.data.unshift({
            id: "all",
            title: "全部分类",
        })
        searchform.catid = "all"
        cat_ls.value = res.data
    }
}

//清空数据
const emptyData = () => {
    searchform.pfrom = 0
    list_data.value = []
    edit_spec_data.value = []
    is_soll.value = false
    is_bill.value = false
    totalNum.value = 0
    totalpic.value = 0
}

const closeDialog = () => {
    dialogVisible.value = false
}

// 这些方法在原代码中被引用但没有定义，需要添加
const chooseGoods = () => {
    let gd_ls = [];
    list_data_back.value.map((v) => {
        if (v.total_num > 0) {
            v.spec_data.map((vs) => {
                if (vs.list) {
                    vs.list.map((vw) => {
                        if (vw.list) {
                            vw.list.map((vk) => {
                                vk.unit_ls.map((vu) => {
                                    if (vu.number > 0) {
                                        gd_ls.push(vu);
                                    }
                                });
                            });
                        } else {
                            vw.unit_ls.map((vu) => {
                                if (vu.number > 0) {
                                    gd_ls.push(vu);
                                }
                            });
                        }
                    });
                } else {
                    vs.unit_ls.map((vu) => {
                        if (vu.number > 0) {
                            gd_ls.push(vu);
                        }
                    });
                }
            });
        }
    });
    gd_ls.map((v) => {
        list_data_back.value.map((vs) => {
            if (v.gdid == vs.id) {
                v.spec_data = JSON.parse(JSON.stringify(vs.spec_data));
            }
        });
    });
    dialogVisible.value = false;
    emit("determineFun", gd_ls);
}

const determineFilling = (data) => {
    // 需要根据实际业务逻辑实现
    // console.log("规格：", data)
    totalNum.value = 0;
    totalpic.value = 0;
    edit_spec_data.value.push(data);
    list_data.value.map((v) => {
        if (v.id == data.id) {
            v.total_num = data.total_num || 0;
            v.total_pic = data.total_pic || 0;
            v.spec_data = data.spec_data;
        }
    });
    list_data_back.value.map((v) => {
        if (v.id == data.id) {
            v.total_num = data.total_num || 0;
            v.total_pic = data.total_pic || 0;
            v.spec_data = data.spec_data;
        }
        totalNum.value += Number(v.total_num) || 0;
        totalpic.value += Number(v.total_pic) || 0;
    });
    is_bill.value = false;
}

// 暴露给父组件的方法
defineExpose({
    initData,
    shopFillData
})
</script>

<style lang="scss" scoped>
.pop-selectitem-list {
    ::v-deep.search-box-select {
        .el-form {
            display: flex;
        }

        .sele-w {
            margin-right: 10px;
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 14px;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin-top: 10px;
    .summary-info {
        display: flex;
        align-items: center;
        gap: 16px;
    }

    .summary-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .summary-label {
        font-size: 14px;
        color: #64748b;
        font-weight: 500;
    }

    .summary-value {
        font-size: 16px;
        font-weight: 600;
    }

    .summary-value.quantity {
        color: #0f172a;
    }

    .summary-value.amount {
        color: #e11d48;
        font-weight: 700;
        text-shadow: 0 1px 2px rgba(225, 29, 72, 0.1);
    }

    .summary-divider {
        width: 1px;
        height: 20px;
        background-color: #cbd5e1;
    }

    .action-buttons {
        display: flex;
        gap: 12px;
    }

    .btn-cancel {
        border-color: #cbd5e1;
        color: #64748b;
    }

    .btn-confirm {
        background-color: #3b82f6;
        border-color: #3b82f6;
    }
}

.list-box {
    height: 580px;
    overflow: auto;
    padding-right: 10px;

    .list-row {
        padding: 10px 0;
        border-bottom: 1px #f2f2f2 solid;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-right: 30px;
        cursor: pointer;

        .list-info {
            display: flex;
            width: 100%;

            .img-box {
                width: 74px;
                height: 74px;
                margin-right: 10px;
                border-radius: 5px;
                background: #eaeaea;
                overflow: hidden;
                display: flex;
                justify-content: center;
                align-items: center;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                span {
                    font-size: 16px;
                    font-weight: bold;
                }
            }

            .info-box {
                width: calc(100% - 80px);

                .f-num {
                    border-radius: 4px;
                    width: 50px;
                    height: 30px;
                    line-height: 30px;
                    text-align: center;
                    background: #f5772f;
                    color: #fff;
                    font-size: 14px;
                }

                .tag-box {
                    span {
                        border-radius: 3px;
                        background: #3388ff;
                        color: #fff;
                        font-size: 10px;
                        padding: 2px 4px;
                        margin-right: 5px;
                    }
                }
            }
        }

        .list-avitve {
            font-size: 20px;
            color: #3388ff;
        }
    }
}

.list-box::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
}

.list-box::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
    background: #ccc; //rgba(0, 0, 0, 0.0);
    scrollbar-arrow-color: red;
}

.list-box::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, 0);
    border-radius: 0;
    background: rgba(0, 0, 0, 0);
}

::v-deep .el-dialog__body {
    padding: 5px 20px 10px !important;
}

::v-deep .el-form-item {
    margin-bottom: 0 !important;
}
</style>